package org.zhang.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.zhang.shortlink.admin.common.biz.user.UserContext;
import org.zhang.shortlink.admin.dao.entity.GroupDO;
import org.zhang.shortlink.admin.dao.mapper.GroupMapper;
import org.zhang.shortlink.admin.dto.req.ShortLinkGroupUpdateDTO;
import org.zhang.shortlink.admin.dto.resp.ShortLinkGroupVO;
import org.zhang.shortlink.admin.remote.api.ShortLinkRemoteService;
import org.zhang.shortlink.admin.remote.dto.resp.ShortLinkGroupCountVO;
import org.zhang.shortlink.admin.service.GroupService;
import org.zhang.shortlink.admin.utils.RandomStringGenerator;
import org.zhang.shortlink.common.base.BaseDO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author zhang
 * @description 针对表【t_group】的数据库操作Service实现
 * @createDate 2024-04-01 20:40:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO>
        implements GroupService {

    //TODO后续优化
    ShortLinkRemoteService remoteService = new ShortLinkRemoteService() {
    };

    @Override
    public Void saveGroup(String groupName) {
        this.saveGroup(UserContext.getUsername(),groupName);
        return null;
    }

    @Override
    public Void saveGroup(String username, String groupName) {
        //保证gid的唯一性
        String gid = null;
        GroupDO group = null;
        do {
            gid = RandomStringGenerator.generateRandomString();
            LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getGid, gid)
                    .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));;
            group = baseMapper.selectOne(wrapper);
        } while (group!=null);

        GroupDO groupInsert = GroupDO.builder()
                .name(groupName)
                .username(username)
                .gid(gid)
                .sortOrder(1)
                .build();
        baseMapper.insert(groupInsert);
        return null;
    }

    /**
     * 获取当前用户短链接分组列表
     * @return
     */
    @Override
    public List<ShortLinkGroupVO> getShortLinkGroupList() {
        String username= UserContext.getUsername();
        LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(!StrUtil.isBlank(username), GroupDO::getUsername, username)
                .orderByAsc(GroupDO::getSortOrder, BaseDO::getUpdateTime);

        //获取列表
        List<GroupDO> groupDOS = baseMapper.selectList(wrapper);

        //获取gid列表
        List<String> gids = groupDOS.stream().map(GroupDO::getGid).toList();
        List<ShortLinkGroupCountVO> countVOS = remoteService.listGroupShortLinkCount(gids).getData();
        Map<String,Integer> gidMap=new HashMap<>();
        countVOS.stream().forEach(shortLinkGroupCountVO -> {
            gidMap.put(shortLinkGroupCountVO.getGid(),shortLinkGroupCountVO.getShortLinkCount());
        });

        List<ShortLinkGroupVO> ret = groupDOS.stream().map(groupDO -> {
            ShortLinkGroupVO groupVO = BeanUtil.toBean(groupDO, ShortLinkGroupVO.class);
            groupVO.setShortLinkCount(gidMap.get(groupVO.getGid()));
            return groupVO;
        }).toList();

        return ret;

    }

    @Override
    public Void updateGroup(ShortLinkGroupUpdateDTO groupUpdateDTO) {
        LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class).eq(GroupDO::getGid, groupUpdateDTO.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername());
        GroupDO group = GroupDO.builder().name(groupUpdateDTO.getName()).build();
        update(group,wrapper);
        return null;
    }

    @Override
    public Void deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class).eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername());
        baseMapper.delete(wrapper);
        return null;
    }
}




